<!--
	作者：offline
	时间：2018-11-28
	描述：创建送货单
-->

<template>
	<div class="createDelivery">
		<el-dialog
			title="选择采购订单"
			v-if="dialogVisible"
			:visible.sync="dialogVisible"
			width="92%"
			:before-close="handleClose"
			v-dialogDrag
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<el-form
				:model="ruleForm"
				ref="ruleForm"
				label-width="70px"
				:inline-message="true"
				label-position="left"
			>
				<el-row :gutter="10" class="m-condition" v-if="accountType==4">
					<el-col :span="5">
						<el-form-item label="客户" class="rightItem">
							<el-select
								value-key="id"
								v-model="selCompanyCode"
								placeholder="请选择客户"
								@change="companyChange"
								filterable
							>
								<el-option
									v-for="item in comOptions"
									:key="item.id"
									:label="item.companyName"
									:value="item"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-form-item label="采购单号" class="rightItem">
							<el-input v-model="purOrdNo" placeholder="请输入采购订单号" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="订单日期" class="rightItem">
							<el-date-picker
								v-model="beginDate"
								type="date"
								:placeholder="placeholder.start"
								:picker-options="pickerOptions"
								value-format="yyyy-MM-dd"
								:editable="false"
								:clearable="false"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-date-picker
							v-model="endDate"
							type="date"
							:placeholder="placeholder.end"
							:picker-options="pickerEndOptions"
							value-format="yyyy-MM-dd"
							:editable="false"
							:clearable="false"
						></el-date-picker>
					</el-col>
					<el-col :span="2">
						<el-form-item label-width="0">
							<el-checkbox label="1" v-model="checked" @change="checkChange">按单选择</el-checkbox>
						</el-form-item>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="search(1)" :disabled="btnDis">查询</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="add">确定</el-button>
					</el-col>
				</el-row>
				<el-row :gutter="10" class="m-condition" v-if="accountType==1">
					<el-col :span="7">
						<el-form-item label="公司" class="rightItem">
							<el-select
								value-key="id"
								v-model="selCompanyCode"
								placeholder="请选择公司"
								@change="selectCompany"
								ref="content"
								filterable
							>
								<el-option
									v-for="item in comOptions"
									:key="item.id"
									:label="item.companyName"
									:value="item"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="采购单号" class="rightItem">
							<el-input v-model="purOrdNo" placeholder="请输入采购订单号" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="订单日期" class="rightItem">
							<el-date-picker
								v-model="beginDate"
								type="date"
								:placeholder="placeholder.start"
								:picker-options="pickerOptions"
								value-format="yyyy-MM-dd"
								:editable="false"
								:clearable="true"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-date-picker
							v-model="endDate"
							type="date"
							:placeholder="placeholder.end"
							:picker-options="pickerEndOptions"
							value-format="yyyy-MM-dd"
							:editable="false"
							:clearable="true"
						></el-date-picker>
					</el-col>
				</el-row>
				<el-row :gutter="10" class="m-condition" v-if="accountType==1">
					<el-col :span="7">
						<el-form-item label="供应商" class="rightItem">
							<el-select
								filterable
								clearable
								v-model="supplierCode"
								placeholder="请选择供应商"
								@focus="focusMethod"
								@clear="supplierOptions=allSupplier"
								@change="supplierChange"
								:filter-method="filterSupplier"
							>
								<el-option
									v-for="item in supplierOptions"
									:key="item.id"
									:label="item.supplierName"
									:value="item.supplierCode"
								>
									<span style="float: left">{{ item.supplierName }}</span>
									<span style="float: right; color: #8492a6; font-size: 13px">{{ item.supplierCode }}</span>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="3">
						<el-form-item label-width="0">
							<el-checkbox label="1" v-model="checked" @change="checkChange">按单选择</el-checkbox>
						</el-form-item>
					</el-col>
					<el-col :span="2" :offset="10">
						<el-button type="primary" @click="search(1)" :disabled="btnDis">查询</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="add">确定</el-button>
					</el-col>
				</el-row>
			</el-form>
			<div class="dialogBody" :style="{'top':accountType==1?'80px':'45px'}">
				<agGridComponents
					ref="agGridComponent"
					:getGridOptions="gridOptions"
					:getColumnDefs="columnDefs"
					:getRowSelection="rowSelection"
					:isColFit="true"
				></agGridComponents>
			</div>
			<div slot="footer" class="dialog-footer">
				<!-- <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @prev-click="handlePrevClick"
          @next-click="handleNextClick"
          :current-page="currentPage"
          :page-sizes="[30,50,100,150,200]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
				></el-pagination>-->
			</div>
		</el-dialog>
		<!-- 选择送货计划弹窗 -->
		<selectPlanDialog
			v-if="planDialogVisible"
			:dialogVisible="planDialogVisible"
			:supplierOptions="supplierOptions"
			@addPlan="addPlan"
			@closePlanDialog="closePlanDialog"
			@companyChange="customerChange"
			@supplierChange="supplierChange"
		></selectPlanDialog>
		<div class="m-window" v-if="componentShow">
			<deliveryComponents
				@cancelComponents="cancelComponents"
				@viewOrder="viewOrder"
				:getClickValue="getClickValue"
				:pageLayOut="pageLayOut"
				:supplierInfo="supplierInfo"
				:companyInfo="companyInfo"
				@selectBill="handleCommand"
				ref="deliveryComponents"
			></deliveryComponents>
		</div>
		<div class="m-window" v-if="orderShow">
			<purOrderDetailsComponents
				@cancelComponents="cancelComponents"
				:getClickValue="order"
				:ordStatus="ordStatus"
			></purOrderDetailsComponents>
		</div>
	</div>
</template>

<script>
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
import agGridComponents from "@/components/agGridComponents.js";
import authInfo from "@/public/authInfo.js";
import deliveryComponents from "@/views/myLogistics/deliveryComponents.vue";
import selectPlanDialog from "@/components/selectPlanDialog.vue";
import supplierInfo from "@/public/supplierInfo.js";
import addOperation from "@/public/addOperation.js";
import serviceTime from "@/public/serverTime.js";
import Msg from "@/public/message.js";
import purOrderDetailsComponents from "@/views/purchase/purOrderDetailsComponents";

export default {
	data () {
		return {
			ruleForm: {},
			dialogVisible: false,
			planDialogVisible: false,
			selCompanyCode: "",
			comOptions: [],
			gridOptions: "",
			columnDefs: "",
			beginDate: "",
			endDate: "",
			purOrdNo: "",
			btnShow: false,
			totalOrderAmount: 0,
			totalCanSendAmount: 0,
			checked: true,
			pickerOptions: {
				disabledDate: this.disabledStartDate
			},
			pickerEndOptions: {
				disabledDate: this.disabledEndDate
			},
			componentShow: false,
			currentPage: 1,
			pageSize: 30,
			total: 0,
			supplierInfo: [],
			rowData: [],
			getClickValue: "",
			pageLayOut: "add",
			companyInfo: "",
			rowSelection: "multiple",
			btnDis: false,
			current: 0,
			textChange: 0,
			placeholder: {
				start: '',
				end: ''
			},
			orderShow: false,
			order: { id: '' },
			ordStatus: '',
			// 账户类型4供应商账户，1为内部用户   
			accountType: this.$global.user.userTypeId,
			supplierOptions: [],
			allSupplier: [],
			supplierCode: ''
		}
	},
	props: {
		removeTab: {
			type: Function
		}
	},
	watch: {
		selCompanyCode () {
			//客户
			this.current = 1;
		},
		purOrdNo (val) {
			//采购单号
			if (val)
				this.textChange = 1;
			else
				this.textChange = 0;
		},
		beginDate (val) {
			this.current = 1;
		},
		endDate () {
			this.current = 1;
		}
	},
	methods: {
		// 多选框状态改变回调   
		checkChange (val) {
			this.$refs.agGridComponent.gridOptions.api.forEachNode(function (node) {
				node.setSelected(false);
			})
		},
		//  限制开始日期选择范围
		disabledStartDate (time) {
			if (this.endDate)
				return time.getTime() > new Date(this.endDate).getTime();
		},
		//  限制结束日期选择范围
		disabledEndDate (time) {
			if (this.beginDate)
				return time.getTime() < (new Date(this.beginDate).getTime() - 3600 * 1000 * 24);
		},
		// 选择订单明细
		rowSelected (params) {
			if (this.checked) {
				if (params.node.selected) {
					this.$refs.agGridComponent.gridOptions.api.forEachNode(function (node) {
						if (node.data.purOrdNo === params.data.purOrdNo)
							node.setSelected(true);
						else
							node.setSelected(false);
					})
				} else {
					this.$refs.agGridComponent.gridOptions.api.forEachNode(function (node) {
						if (node.data.purOrdNo === params.data.purOrdNo)
							node.setSelected(false);
					})
				}
			} else {
				const { purOrdNo, purOrdMxNo } = params.data
				if (params.node.selected) {
					this.$refs.agGridComponent.gridOptions.api.forEachNode(function (node) {
						if (node.data.purOrdNo !== purOrdNo)
							node.setSelected(false);
					})
				} else {
					this.$refs.agGridComponent.gridOptions.api.forEachNode(function (node) {
						if (node.data.purOrdNo === purOrdNo && node.data.purOrdMxNo === purOrdMxNo)
							node.setSelected(false);
					})
				}
			}
		},
		handleSizeChange (params) {
			this.currentPage = 1;
			this.pageSize = params;
			this.search();
		},
		handleCurrentChange (params) {
			if (this.textChange === 1 || this.current === 1)
				this.currentPage = 1;
			else
				this.currentPage = params;
			this.search();
		},
		handlePrevClick (params) {
			if (this.textChange === 1 || this.current === 1)
				this.currentPage = 1;
			else
				this.currentPage = params;
		},
		handleNextClick (params) {
			if (this.textChange === 1 || this.current === 1)
				this.currentPage = 1;
			else
				this.currentPage = params;
		},
		create () {
			//   this.dialogVisible = true;
			this.btnShow = false;
			this.checked = true
			let that = this;
			this.$nextTick(_ => {
				that.totalCanSendAmount = 0;
				that.totalOrderAmount = 0;
				that.rowData = [];
				that.$refs.agGridComponent.gridOptions.api.setRowData([]);
				that.$refs.agGridComponent.gridOptions.api.setPinnedBottomRowData(that.createBottomRow(1, "Bottom"));
			})
		},
		// 选择下拉项回调
		handleCommand (command) {
			switch (command) {
				case "order":
					this.dialogVisible = true;
					this.btnShow = false;
					this.endDate = new Date().Format("yyyy-MM-dd")
					this.beginDate = new Date(Date.parse(this.endDate) - 3600 * 1000 * 24 * 30).Format("yyyy-MM-dd")
					let that = this;
					this.$nextTick(_ => {
						that.totalCanSendAmount = 0;
						that.totalOrderAmount = 0;
						that.rowData = [];
						that.$refs.agGridComponent.gridOptions.api.setRowData([]);
						that.$refs.agGridComponent.gridOptions.api.setPinnedBottomRowData(that.createBottomRow(1, "Bottom"));
					})
					break;
				case "plan":
					console.log("2")
					this.planDialogVisible = true
					this.btnShow = false;
					break
			}
		},
		handleClose (done) {
			done();
			this.total = 0;
			this.currentPage = 1;
			this.pageSize = 30;
			this.btnShow = true;
		},
		companyChange (params) {
			this.search();
			this.companyInfo = params;
		},
		// 供应商账户选择客户回调
		customerChange (params) {
			if (this.accountType == 1) {
				this.getAuthSuppliers(params.companyCode)
			}
			this.companyInfo = params;
		},
		// 内部账户选择公司回调
		selectCompany (val) {
			this.getAuthSuppliers(val.companyCode)
			this.companyInfo = val
		},
		search (flag) {
			if (this.beginDate != "" && this.beginDate != null && this.endDate != "" && this.endDate != null) {
				if (this.beginDate > this.endDate) {
					this.$alert("提示：开始日期不能大于结束日期", {
						showClose: false,
						confirmButtonText: "确定",
						customClass: "alertPrompt"
					});
					return;
				}
			}
			if (!this.selCompanyCode) {
				this.$alert("提示：请选择客户", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			var obj = {};
			var that = this;
			if (this.selCompanyCode)
				obj.companyCode = this.selCompanyCode.companyCode;
			if (this.$global.user.userTypeId == "4")
				obj.supplierCode = this.supplierInfo[0].supplierCode;
			else
				obj.supplierCode = this.supplierCode
			if (this.purOrdNo)
				obj.purOrdNo = this.purOrdNo;
			if (this.beginDate != "" && this.beginDate != null)
				obj.Begin_Date = this.beginDate
			else if ((this.beginDate == "" || this.beginDate == null) && this.endDate != "" && this.endDate != null)
				obj.Begin_Date = this.endDate
			if (this.endDate != "" && this.endDate != null)
				obj.End_Date = this.endDate
			else if ((this.endDate == "" || this.endDate == null) && this.beginDate != "" && this.beginDate != null)
				obj.End_Date = this.beginDate;
			if (flag === 1)
				this.currentPage = 1;
			//   obj.current = this.currentPage;//this.currentPage;
			//   obj.size = this.pageSize;
			if (!obj.supplierCode) {
				this.$alert("供应商不能为空", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			this.$refs.agGridComponent.loading = true;
			this.btnDis = true;
			_Api.getWaitDeliveryPurOrder(obj).then(function (response) {
				that.$refs.agGridComponent.loading = false;
				that.btnDis = false;
				that.current = 0;
				that.textChange = 0;
				var data = response.data;
				if (data.code == "1") {
					if (data.total > 0) {
						that.rowData = data.rows.splice(0);
						that.$refs.agGridComponent.gridOptions.api.setRowData(that.rowData);
						that.totalOrderAmount = 0;
						that.totalCanSendAmount = 0;
						that.$refs.agGridComponent.gridOptions.api.forEachNode(function (node) {
							that.totalOrderAmount = addOperation.accAdd(node.data.orderAmount, that.totalOrderAmount);
							that.totalCanSendAmount = addOperation.accAdd(node.data.deliveryNum, that.totalCanSendAmount);
							that.$refs.agGridComponent.gridOptions.api.setPinnedBottomRowData(that.createBottomRow(1, "Bottom"));
						})
						that.total = data.total;
						that.$refs.agGridComponent.rowDataChange = true;
					} else {
						that.rowData = [];
						that.$refs.agGridComponent.gridOptions.api.setRowData([]);
						that.total = 0;
						that.totalOrderAmount = 0;
						that.totalCanSendAmount = 0;
						that.$refs.agGridComponent.gridOptions.api.setPinnedBottomRowData(that.createBottomRow(1, "Bottom"));
					}
				} else {
					that.$alert(data.info, {
						showClose: false,
						confirmButton: "确定",
						customClass: "alertFailure"
					});
					that.rowData = [];
					that.$refs.agGridComponent.loading = false;
					that.$refs.agGridComponent.gridOptions.api.setRowData([]);
					that.total = 0;
				}
			}).catch((err) => {
				that.$alert(err.data.message, {
					showClose: false,
					confirmButton: "确定",
					customClass: "alertFailure"
				});
				that.btnDis = false;
				that.$refs.agGridComponent.loading = false;
				that.$refs.agGridComponent.gridOptions.api.setRowData([]);
				that.total = 0;
				that.current = 0;
				that.textChange = 0;
			})
		},
		add () {
			//   if (this.$global.user.userTypeId != "4") {
			//     this.$alert("提示：当前角色暂不允许添加数据！", {
			//       showClose: false,
			//       confirmButtonText: "确定",
			//       customClass: "alertPrompt"
			//     });
			//     return;
			//   }
			var rows = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
			if (rows.length <= 0) {
				this.$alert("提示：请选择需要创建的数据", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			this.btnShow = false;
			this.dialogVisible = false;
			//   this.componentShow = true;
			this.getClickValue = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
			this.$refs['deliveryComponents'].createdDelivery(this.getClickValue, this.companyInfo)
		},
		// 确认选择送货计划回调
		addPlan (rows) {
			this.btnShow = false;
			this.planDialogVisible = false;
			this.componentShow = true;
			this.getClickValue = rows
			this.$refs['deliveryComponents'].createdDelivery(this.getClickValue, this.companyInfo)
		},
		// 关闭选择送货计划弹窗
		closePlanDialog () {
			this.total = 0;
			this.currentPage = 1;
			this.pageSize = 30;
			this.btnShow = true;
			this.planDialogVisible = false
		},
		createBottomRow (count, prefix) {
			var result = [{
				matName: "合计",
				orderAmount: this.totalOrderAmount,
				canSendAmount: this.totalCanSendAmount
			}];
			return result;
		},
		cancelComponents (msg) {
			if (msg) {
				// this.componentShow = false;
				// this.btnShow = true;
				this.removeTab()
				this.orderShow = false
			}
		},
		// 查看订单详情
		viewOrder (orderObj) {
			this.orderShow = true
			this.componentShow = false;
			this.btnShow = false;
			this.order.id = orderObj.orderId
			this.ordStatus = orderObj.ordStatus
		},
		// 获取当前公司所有供应商
		getAuthSuppliers (companyCode) {
			this.formLoading = true
			this.supplierCode = ''
			this.$http.getAuthSupplierByCompanyCode({ name: companyCode }).then(({ data }) => {
				this.formLoading = false
				if (data.code == 1) {
					this.supplierOptions = data.rows
					this.allSupplier = data.rows
				} else {
					Msg.showErrorMsg(data.info)
				}
			}).catch(err => {
				this.formLoading = false
				Msg.showErrorMsg(err.data.message)
			})
		},
		// 筛选供应商
		filterSupplier (value) {
			if (value != '') {
				this.supplierOptions = this.allSupplier.filter(item => item.supplierCode.indexOf(value) > -1 || item.supplierName.indexOf(value) > -1)
			} else {
				this.supplierOptions = this.allSupplier
			}
		},
		// 供应商下拉框获取焦点
		focusMethod () {
			if (!this.selCompanyCode) {
				Msg.showPopMsg('请先选择公司!')
				this.$refs.content.focus();
			}
		},
		// 供应商选择框下拉
		supplierChange (val) {
			for (let i = 0; i < this.supplierOptions.length; i++) {
				if (val == this.supplierOptions[i].supplierCode) {
					this.supplierName = this.supplierOptions[i].supplierName
					this.supplierInfo.push({
						supplierName: this.supplierOptions[i].supplierName,
						supplierCode: this.supplierOptions[i].supplierCode,
						id: this.supplierOptions[i].id
					})
					return
				}
			}
		},
	},
	mounted () {
		this.dialogVisible = false;
		// this.btnShow = true;
		var that = this;
		authInfo.getAuthInfo().then((authCompanyInfo) => {
			that.comOptions = authCompanyInfo;
		});
		serviceTime.getServiceTime().then((serviceTime) => {
			that.beginDate = new Date((serviceTime.getTime() - 604800000)).Format("yyyy-MM-dd");
			that.endDate = serviceTime.Format("yyyy-MM-dd");
			that.placeholder.start = "开始日期"
			that.placeholder.end = "结束日期"
		});
		if (this.$global.user.userTypeId == "4") {
			this.supplierInfo.push(this.$global.supplierData);
			if (this.supplierInfo[0] == null) {
				supplierInfo.getUserInfo(this.$global.user.userName).then((supplierInfo) => {
					that.supplierInfo = supplierInfo;
					that.componentShow = true
				})
			} else {
				that.componentShow = true
			}
		} else {
			that.componentShow = true
		}
	},
	beforeMount () {
		this.gridOptions = {
			context: {
				componentParent: this
			},
			enableColResize: true,
			localeText: localeText,
			//   getContextMenuItems: [],
			defaultColDef: {
				menuTabs: []
			},
			pinnedBottomRowData: this.createBottomRow(1, "Bottom"),
			getRowStyle: function (params) {
				if (params.node.rowPinned) {
					return { 'color': 'red', 'font-weight': "bold" }
				}
			},
			onRowSelected: this.rowSelected,
			suppressRowClickSelection: true//单元格选中,false为选中整行
		};

		this.columnDefs = [
			{ headerName: "采购订单号", field: "purOrdNo", width: 140, checkboxSelection: true },
			{ headerName: "订单行号", field: "purOrdMxNo", width: 100 },
			{				headerName: "订单日期", field: "purOrdDate", width: 100, cellRenderer: function (params) {
					if (params.value)
						return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format("yyyy-MM-dd");
				}
			},
			{ headerName: "物料描述", field: "matName", width: 140 },
			{ headerName: "订单数量", field: "orderAmount", width: 100 },
			{ headerName: "单位", field: "unitCode", width: 70 },
			//jjc
			//{	headerName:"订单数量",field:"priceAmount"},
			//{	headerName:"单位",field:"priceUnit"},
			{				headerName: "可发数量", field: "canSendAmount", width: 100, cellRenderer: function (params) {
					if (!params.value)
						return '<span class="ag-icon">0</span>';
					else
						return '<span class="ag-icon">' + params.value + '</>'
				}
			}];
	},
	components: {
		agGridComponents,
		deliveryComponents,
		selectPlanDialog,
		purOrderDetailsComponents
	}
}
</script>

<style lang="less">
.createDelivery {
	.el-dialog__body {
		height: 500px;
		position: relative;
		.el-form {
			.el-form-item {
				margin-bottom: 10px;
			}
		}
	}
	.dialogBody {
		position: absolute;
		top: 45px;
		bottom: 0px;
		left: 0px;
		right: 0px;
	}
	.el-dialog__footer {
		padding-top: 0;
		margin-top: 0px;
		text-align: center;
		.dialog-footer {
			button {
				width: 10px;
			}
		}
	}
}
</style>